package com.lxg.controller.userController;

import com.lxg.dao.UserDao;
import com.lxg.pojo.*;
import com.lxg.service.booksService.BooksShowService;
import com.lxg.service.firstService.LoginService;
import com.lxg.service.userService.UserBorrowService;
import com.lxg.service.userService.UserProblemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Controller
public class UsersController {
    @Autowired
    UserBorrowService userBorrowService;
    @Autowired
    UserProblemService userProblemService;

    @Autowired
    BooksShowService booksShowService;

    @Autowired
    UserDao userDao;

    /*@RequestMapping(value = "/updateUser",method = RequestMethod.POST)
    public String  updateUser(String username, String password, String name, String sno,
                              String grade, String email, String phone, HttpSession session){
        System.out.println("username"+username);
        boolean b = userBorrowService.updateUser
                (username, password, name, sno, grade, email, phone);
        session.setAttribute("result",b);
        return "/user/self";
    }*/
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public String updateUser(User user, HttpSession session) {
        System.out.println("grade:" + user.getGrade());
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        String name = user.getName();
        String sno = user.getSno();
        String grade = user.getGrade();
        String phone = user.getPhone();

        User olduser = (User) session.getAttribute("user");
        String Oldusername = olduser.getUsername();
//        String Oldpassword=olduser.getPassword();
        String Oldemail = olduser.getEmail();
        String OldSno = olduser.getSno();
        Integer uid = olduser.getUid();


        User user1 = userDao.checkUsername(username);
        User user2 = userDao.checkEmail(email);
        User user3 = userDao.checkSno(sno);


        if (!username.equals(Oldusername) && !email.equals(Oldemail) && !sno.equals(OldSno)) {


            if (user1 == null && user2 == null && user3 == null) {
                boolean b = userBorrowService.updateUser
                        (username, password, name, sno, grade, email, phone, uid);
                session.setAttribute("result", b);
                User updateuser = userDao.getUserByUid(uid);
                session.setAttribute("user", updateuser);
            }

        } else if (!username.equals(Oldusername) && email.equals(Oldemail) && sno.equals(OldSno)) {

            if (user1 == null) {
                boolean b = userBorrowService.updateUser
                        (username, password, name, sno, grade, email, phone, uid);
                session.setAttribute("result", b);
                User updateuser = userDao.getUserByUid(uid);
                session.setAttribute("user", updateuser);
            }
        } else if (username.equals(Oldusername) && !email.equals(Oldemail) && sno.equals(OldSno)) {

            if (user2 == null) {
                boolean b = userBorrowService.updateUser
                        (username, password, name, sno, grade, email, phone, uid);
                session.setAttribute("result", b);
                User updateuser = userDao.getUserByUid(uid);
                session.setAttribute("user", updateuser);
            }
        } else if (username.equals(Oldusername) && email.equals(Oldemail) && !sno.equals(OldSno)) {

            if (user3 == null) {
                boolean b = userBorrowService.updateUser
                        (username, password, name, sno, grade, email, phone, uid);
                session.setAttribute("result", b);
                User updateuser = userDao.getUserByUid(uid);
                session.setAttribute("user", updateuser);
            }
        } else if (username.equals(Oldusername) && email.equals(Oldemail) && sno.equals(OldSno)) {
            boolean b = userBorrowService.updateUser
                    (username, password, name, sno, grade, email, phone, uid);
            session.setAttribute("result", b);
            User updateuser = userDao.getUserByUid(uid);
            session.setAttribute("user", updateuser);
        }
        return "/user/self";
    }


    /**
     * 还书service
     * @param uid
     * @param bid
     * @return
     */
    @RequestMapping("/ReturnBookService")
    public String ReturnBookService(Integer uid,Integer bid, HttpSession session){
        boolean b = userBorrowService.ReturnBookService(uid, bid);
        session.setAttribute("result",b);
        return "/index";
    }


    /**
     * 借书service
     * @param uid
     * @param bid
     * @return
     */
    @RequestMapping("/BorrowBookService")
    public String BorrowBookService(Integer uid,Integer bid, HttpSession session){
        boolean b = userBorrowService.BorrowBookService(uid, bid);
        session.setAttribute("result",b);
        return "/index";
    }


    /**
     * 添加一个问题
     *
     */
    @RequestMapping("/user/addProblem")
    public String  addProblem(Problem problem, HttpServletRequest request,HttpSession session){
        Integer uid = problem.getUid();
        String name = problem.getName();
        String page = problem.getPage();
        String body = problem.getBody();
        String phone = problem.getPhone();


        if(uid == null || name == "" || page == "" || body == "" || phone == "" ){
            boolean addResult=false;
            request.setAttribute("addResult",false);
            return "/user/problem";
        }else{

            boolean b = userProblemService.addProblem(uid, name, page, body, phone);
            request.setAttribute("addResult",b);
            return "/user/problem";
        }
    }


    //放入书架
    @RequestMapping("/user/addMyBooks")
    public String  addMyBook(HttpServletRequest request){
        //获取传过来的bid
        Integer bid = Integer.valueOf(request.getParameter("bid"));
        String suid = request.getParameter("uid");
        Integer uid;
        if(suid=="" || suid.equals("null")){
            uid=0;
        }else{
            uid = Integer.valueOf(suid);
        }

        if(uid==0){
            boolean b = false;
            return "redirect:/?addResult="+b;
        }


        //根据bid查找书架里面的书
        Borrow borrow = userBorrowService.getBorrow(bid,uid);

        //查找bid对应图书信息
        Books book = booksShowService.getBookByBid(bid);
        String bookname = book.getName();
        String author = book.getAuthor();

        System.out.println("uid="+uid);
        System.out.println("bid="+bid);

        Integer deleted = userBorrowService.isDeleted(uid, bid);


        if(borrow != null){

            if(deleted==1){
                boolean b = userBorrowService.addMyBook(bid,uid, bookname, author, 1, 0);
                return "redirect:/?addResult="+b;
            }else {
                //获取原来的数量
                Integer num1 = borrow.getNum();
                Integer num= num1+1;
                //修改书架中图书的信息
                boolean b = userBorrowService.updateBorrow(bid,uid, num);
                return "redirect:/?addResult="+b;
            }
        }else{
            boolean b = userBorrowService.addMyBook(bid,uid, bookname, author, 1, 0);
            return "redirect:/?addResult="+b;
        }
    }


    //立即借阅
    @RequestMapping("/user/indexborrowBooks")
    public String indexborrowBooks(HttpServletRequest request){
        //获取传过来的bid和uid
        Integer bid = Integer.valueOf(request.getParameter("bid"));
        String suid = request.getParameter("uid");
        Integer uid;
        if(suid==""|| suid.equals("null")){
            uid=0;
        }else{
            uid = Integer.valueOf(suid);
        }

        if(uid==0){
            boolean b = false;
            return "redirect:/?borrowResult="+b;
        }

        //根据bid查找书架里面的书
        Borrow borrow = userBorrowService.getBorrow(bid,uid);

        //查找bid对应图书信息
        Books book = booksShowService.getBookByBid(bid);
        String bookname = book.getName();
        String author = book.getAuthor();

        Integer deleted = userBorrowService.isDeleted(uid, bid);

        if(borrow != null){

            if(deleted==1) {
                boolean b = userBorrowService.addMyBook(bid, uid, bookname, author, 1, 0);
            }else{
                //获取原来的数量
                Integer num1 = borrow.getNum();
                Integer num= num1+1;
                //修改书架中图书的信息
                boolean b = userBorrowService.updateBorrow(bid,uid, num);
            }


            //获取当前时间
            SimpleDateFormat simpleDateFormat =
                    new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
            Date date = new Date(System.currentTimeMillis());
            String begintime = simpleDateFormat.format(date);

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 7);
            String endtime = simpleDateFormat.format(calendar.getTime());


            //添加借阅记录
            //查找根据uid 和bid查找借阅记录
            History historyByUidAndBid = userBorrowService.getHistoryByUidAndBid(uid, bid);
            if(historyByUidAndBid!=null){
                //获取原来的数量
                Integer num2 = historyByUidAndBid.getNum();

                if(num2>=10){
                    return "redirect:/?maxResult="+false;
                }

                userBorrowService.updateHistory(uid, bid, endtime, num2 + 1);
            }else{
                userBorrowService.addHistory(uid, bid, bookname, author, begintime, endtime, 1,0);
            }
            return "redirect:/?borrowResult="+true;
        }else{
            boolean b = userBorrowService.addMyBook(bid,uid, bookname, author, 1, 0);
            //获取当前时间
            SimpleDateFormat simpleDateFormat =
                    new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
            Date date = new Date(System.currentTimeMillis());
            String begintime = simpleDateFormat.format(date);

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 7);
            String endtime = simpleDateFormat.format(calendar.getTime());


            //添加借阅记录
            //查找根据uid 和bid查找借阅记录
            History historyByUidAndBid = userBorrowService.getHistoryByUidAndBid(uid, bid);
            if(historyByUidAndBid!=null){
                //获取原来的数量
                Integer num2 = historyByUidAndBid.getNum();
                if(num2>=10){
                    return "redirect:/?maxResult="+false;
                }
                //更新
                userBorrowService.updateHistory(uid,bid,endtime,num2+1);
            }else{
                userBorrowService.addHistory(uid, bid, bookname, author, begintime, endtime, 1,0);
            }
            return "redirect:/?borrowResult="+b;
        }
    }


    @RequestMapping("/user/deleteMyBook")
    public String deleteMyBook(HttpServletRequest request){
        Integer bid = Integer.valueOf(request.getParameter("bid"));
        String suid = request.getParameter("uid");
        Integer uid;
        if(suid==""){
            uid=0;
        }else{
            uid = Integer.valueOf(suid);
        }

        if(uid==0){
            boolean b = false;
            return "redirect:/user/myBook?borrowResult="+b;
        }

        Borrow borrow = userBorrowService.getBorrow(bid, uid);
        Integer status = borrow.getStatus();
        if(status==1){
            return "redirect:/user/myBook?deleteResult="+false;
        }else{
            userBorrowService.deleteBorrow(bid,uid);
            return "redirect:/user/myBook";
        }

    }


    //借阅
    @RequestMapping("/user/borrowBook")
    public String borrowBook(HttpServletRequest request){
        //获取传过来的bid和uid
        Integer bid = Integer.valueOf(request.getParameter("bid"));
        String suid = request.getParameter("uid");
        Integer days = Integer.valueOf(request.getParameter("days"));
        Integer uid;
        if(suid==""){
            uid=0;
        }else{
            uid = Integer.valueOf(suid);
        }

        if(uid==0){
            boolean b = false;
            return "redirect:/user/myBook?borrowResult="+b;
        }

        //查找bid对应图书信息
        Books book = booksShowService.getBookByBid(bid);
        String bookname = book.getName();
        String author = book.getAuthor();

        //获取当前时间
        SimpleDateFormat simpleDateFormat =
                new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        String begintime = simpleDateFormat.format(date);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, days);
        String endtime = simpleDateFormat.format(calendar.getTime());


        //添加借阅记录
        //查找根据uid 和bid查找借阅记录
        History historyByUidAndBid = userBorrowService.getHistoryByUidAndBid(uid, bid);




        Borrow borrow = userBorrowService.getBorrow(bid,uid);
        if(historyByUidAndBid!=null){
            //获取原来的数量
            Integer num2 = historyByUidAndBid.getNum();
            Integer num = borrow.getNum()+num2;


            System.out.println("num: " + num);

            if(num2>=10){
                return "redirect:/user/myBook?maxResult="+false;
            }


            //更新
            userBorrowService.updateHistory(uid,bid,endtime,num);
        }else{
            Integer num = borrow.getNum();
            userBorrowService.addHistory(uid, bid, bookname, author, begintime, endtime, num,0);
        }
        return "redirect:/user/myBook?borrowResult="+true;
    }
}
